import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'home.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  TextEditingController nameTextEditingController = TextEditingController();
  TextEditingController passwordTextEditingController = TextEditingController();
  static const methodChannel = MethodChannel('com.sz.callPhoneTest.call_phone_test');
  bool showLoginError = false;
  bool isLogging = false;
  String loginErrorMsg = '';


  @override
  void initState() {
    super.initState();


  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.symmetric(horizontal: 18),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              autofocus: true,
              keyboardType: TextInputType.emailAddress,
              controller: nameTextEditingController,
              decoration: const InputDecoration(
                  labelText: "用户名",
                  labelStyle: TextStyle(fontSize: 16),
                  hintText: "请输入用户名",
                  helperStyle: TextStyle(fontSize: 16),
                  prefixIcon: Icon(Icons.person)
              ),
            ),
            TextField(
              controller: passwordTextEditingController,
              decoration: const InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  prefixIcon: Icon(Icons.lock)
              ),
              obscureText: true,
            ),

            const SizedBox(height: 20),

            if (showLoginError)
              Align(
                alignment: Alignment.centerLeft,
                child: Text(loginErrorMsg, style: TextStyle(fontSize: 16, color: Colors.red)),
              )
            else
              Container(),

            const SizedBox(height: 30),

            GestureDetector(
              onTap: _login,
              child: Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: 50,
                color: Colors.blue,
                child: Text(isLogging == true? '登录中...':'登录',
                    style: TextStyle(fontSize: 16, color: Colors.white)),
              ),
            )
          ],
        ),
      ),
    );
  }

  void _login() async {
    if (isLogging) {
      return;
    }

    setState(() {
      isLogging = true;
    });

    String name = nameTextEditingController.text;
    String password = passwordTextEditingController.text;

    if (nameTextEditingController.text.isEmpty) {
      setState(() {
        isLogging = false;
        showLoginError = true;
        loginErrorMsg = '用户名不能为空';
      });
      return;
    }
    if (passwordTextEditingController.text.isEmpty) {
      setState(() {
        isLogging = false;
        showLoginError = true;
        loginErrorMsg = '密码不能为空';
      });
      return;
    }

    try{
      int result = await methodChannel.invokeMethod('login', {'name': name, 'password': password});
      if (result == 200) {
        Future.delayed(const Duration(seconds: 1), () {
          Navigator.pushReplacement(context,
            MaterialPageRoute(
                builder: (context) {
                  return HomePage();
                }),
          );
        });
      } else {
        setState(() {
          isLogging = false;
          showLoginError = true;
          loginErrorMsg = '用户名或密码错误';
        });
      }
    }catch(e) {
      setState(() {
        isLogging = false;
        showLoginError = true;
        loginErrorMsg = e.toString();
      });
    }


  }


}
